<template>
  <div>
    <BasicTable
      @register="registerTable"
      :can-resize="true"
      :bordered="true"
      :striped="false"
      :data-source="DutyStaffData.staffs"
    >
      <template #toolbar>
        <a-button type="primary" @click="onAddDutyStaff"> 新增 </a-button>
      </template>

      <template #action="{ record }">
        <TableAction
          :actions="[
            {
              icon: 'clarity:note-edit-line',
              label: '编辑',
              onClick: onEditDutyStaff.bind(null, record),
            },
            {
              icon: 'ant-design:delete-outlined',
              label: '删除',
              color: 'error',
              popConfirm: {
                title: '是否确认删除',
                confirm: onDeleteDutyStaff.bind(null, record),
              },
            },
          ]"
        />
      </template>
    </BasicTable>

    <addOrUpdateStaff @register="registerAddOrUpdateStaffForm" @success="afterSuccess" />
  </div>
</template>
<script lang="ts">
  import { defineComponent, ref, reactive, provide, onBeforeMount, onUnmounted } from 'vue';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';

  import { OperationTypeEnum } from '/@/enums/appEnum';
  import { useMessage } from '/@/hooks/web/useMessage';

  import { getAllDutyStaff, deleteDutyStaff } from '/@/api/duty/dutystaff';
  import { dutyStaffTableColumns } from './dutyStaff.data';
  import { getProjectValidDept } from '/@/api/demo/dept';

  //引入子组件
  import addOrUpdateStaff from './AddOrUpdateStaff.vue';

  //使用modal弹出窗口
  import { useModal } from '/@/components/Modal';
  const { createMessage } = useMessage();

  const [registerAddOrUpdateStaffForm, { openModal: openAddOrUpdateStaffForm }] = useModal();

  export default defineComponent({
    name: 'DutyStaffManagement',
    components: { BasicTable, TableAction, addOrUpdateStaff },
    setup() {
      //定义模块的名称，提供给子孙组件获取使用
      const moduleName = ref('值班人员管理');
      provide('moduleName', moduleName);

      //处理过后的table数据
      const DutyStaffData = reactive({
        staffs: [],
      });
      //部门信息
      let deptsData = [];

      /**
       * 请求后台查询接口返回数据显示
       */
      const [registerTable, { reload }] = useTable({
        title: '值班人员管理',
        // api: getAllDutyStaff, //获取所有值班人员
        columns: dutyStaffTableColumns, //表头数据
        scroll: { y: 500 },
        showTableSetting: true, //是否显示表格设置
        showIndexColumn: true,
        actionColumn: {
          width: 120,
          title: '操作',
          dataIndex: 'action',
          slots: { customRender: 'action' },
          fixed: 'right', //表格操作列是否固定，不设置时默认固定在右侧
        },
        pagination: false, //关闭分页
      });

      onBeforeMount(() => {
        console.log('DOM即将挂载');
        getProjectValidDepts();
        getQueryStaffData();
      });
      onUnmounted(() => {
        console.log('销毁完毕');
      });

      /**
       * 查询值班人员列表
       */
      async function getQueryStaffData() {
        if (DutyStaffData.staffs.length > 0) {
          DutyStaffData.staffs = [];
        }
        getAllDutyStaff()
          .then((res) => {
            console.log('res', res);
            if (res != null) {
              //处理返回数据
              if (res != null) {
                res.forEach((staff) => {
                  let result = {
                    id: staff.id,
                    name: staff.name,
                    dept: staff.dept,
                    deptName: '',
                    phone: staff.phone,
                    cornet: staff.cornet,
                  };
                  //处理部门名称
                  if (deptsData != null && deptsData.length > 0) {
                    deptsData.forEach((dept) => {
                      if (staff.dept == dept.deptid) {
                        result.deptName = dept.name;
                      }
                    });
                  }

                  DutyStaffData.staffs.push(result);
                });
              }
            }
            console.log('DutyStaffData', DutyStaffData);
          })
          .catch((ex) => {
            console.log('catch ', ex);
            createMessage.error(ex.msg);
          });
      }

      /**
       * 打开值班人员新增窗口
       */
      function onAddDutyStaff() {
        //使用props传递数据至子组件，在data参数中指定
        openAddOrUpdateStaffForm(true, { op: OperationTypeEnum.ADD });
      }

      /**
       * 打开值班人员编辑窗口
       */
      function onEditDutyStaff(record: Recordable) {
        openAddOrUpdateStaffForm(true, { op: OperationTypeEnum.EDIT, staff: record });
      }

      /**
       * 删除值班人员
       */
      function onDeleteDutyStaff(record: Recordable) {
        deleteDutyStaff(record.id)
          .then((res) => {
            console.log('res', res);
            //res判断结果：同时==undefined和null
            if (res == undefined && (res == null || Object.keys(res).length == 0)) {
              createMessage.success('删除成功。', 2);
              afterSuccess();
            }
          })
          .catch((ex) => {
            console.log('catch ', ex);
            createMessage.error(ex.msg);
          });
      }

      /**
       * 获取项目有效部门
       */
      function getProjectValidDepts() {
        getProjectValidDept('')
          .then((res) => {
            console.log('res', res);
            res.forEach((dept) => {
              console.log('dept', dept);
              let deptData = {
                deptid: dept.id,
                name: dept.name,
              };
              deptsData.push(deptData);
            });
            console.log('deptsData', deptsData);
          })
          .catch((ex) => {
            console.log('catch ', ex);
            createMessage.error(ex.msg);
          });
      }

      /**
       * 弹窗确认操作之后刷新页面
       */
      function afterSuccess() {
        getQueryStaffData();
      }

      return {
        moduleName,
        registerTable,
        afterSuccess,
        registerAddOrUpdateStaffForm,
        onAddDutyStaff,
        onEditDutyStaff,
        onDeleteDutyStaff,
        getProjectValidDepts,
        getQueryStaffData,
        DutyStaffData,
      };
    },
  });
</script>
